//
//  PayWebView.m
//  奇阅
//
//  Created by 奇阅科技 on 14-11-14.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "PayWebView.h"
#import "QYLoadingView.h"
#define ReadPackage1 @"ReadPackage1"
#define ReadPackage2 @"ReadPackage2"
#define ReadPackage3 @"ReadPackage3"
#define ReadPackage4 @"ReadPackage4"
#define ReadPackage5 @"ReadPackage5"
#define ReadPackage6 @"ReadPackage6"
#import <StoreKit/StoreKit.h>
#import <StoreKit/SKPaymentTransaction.h>
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#import "ZMYNetWorkAPI.h"
#import "AppDelegate.h"
#import "RechargeRecord.h"
#import "ZMYLKDB.h"
#import "MobClick.h"
#import "BookReadPermissions.h"
@interface PayWebView()<SKProductsRequestDelegate, SKPaymentTransactionObserver>
{
    // 产品字典
    NSMutableDictionary *_productDict;
    BOOL isLoadingFinished;
    QYLoadingView *loadingView;
    NSString *buyingProduct;
    NSString *productId;
    NSString *coin_num;
}
@property (weak, nonatomic) IBOutlet UIImageView *loadFailImageView;
@end
@implementation PayWebView

-(void)dealloc{
    NSLog(@"");
}
-(void)awakeFromNib{
    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    [self layoutSubviews];
    self.payWebView.scrollView.bounces = NO;
    self.payWebView.delegate = self;
    self.bearingView.layer.cornerRadius = 10;
    loadingView = [[[NSBundle mainBundle]loadNibNamed:@"QYLoadingView" owner:self options:nil] lastObject];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(reloadWebAgain:)];
    [self.loadFailImageView addGestureRecognizer:tap];
    // 设置购买队列的监听器
//    [self requestProducts];
}   
#pragma mark 询问苹果的服务器能够销售哪些商品
- (void)requestProducts
{
    if (loadingView.superview == nil) {
        [loadingView showView];
    }
    // 能够销售的商品
    NSSet *set = [[NSSet alloc] initWithObjects:ReadPackage1, ReadPackage2, ReadPackage3, ReadPackage4, ReadPackage5, ReadPackage6, nil];
    
    // "异步"询问苹果能否销售
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
    
    request.delegate = self;
    
    // 启动请求
    [request start];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    if (_productDict == nil) {
        _productDict = [NSMutableDictionary dictionaryWithCapacity:response.products.count];
    }
    
    for (SKProduct *product in response.products) {
        // 激活了对应的销售操作按钮，相当于商店的商品上架允许销售
        NSLog(@"%@", product.productIdentifier);
        
        if ([product.productIdentifier isEqualToString:ReadPackage1]) {
        }
        
        if ([product.productIdentifier isEqualToString:ReadPackage2]) {
        }
        if ([product.productIdentifier isEqualToString:ReadPackage3]) {
        }
        if ([product.productIdentifier isEqualToString:ReadPackage4]) {
        }
        if ([product.productIdentifier isEqualToString:ReadPackage5]) {
        }
        if ([product.productIdentifier isEqualToString:ReadPackage6]) {
        }
        // 填充商品字典
        [_productDict setObject:product forKey:product.productIdentifier];
    }
    if (loadingView.superview == nil) {
        [loadingView showView];
    }
    [self buyProduct:_productDict[buyingProduct]];
}
#pragma mark - 用户决定购买商品
- (void)buyProduct:(SKProduct *)product
{
    // 要购买产品(店员给用户开了个小票)
    SKPayment *payment = [SKPayment paymentWithProduct:product];
    
    // 去收银台排队，准备购买(异步网络)
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}
#pragma mark - SKPaymentTransaction Observer
#pragma mark 购买队列状态变化
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    if (loadingView.superview == nil) {
        [loadingView showView];
    }
    // 调试
    for (SKPaymentTransaction *transaction in transactions) {
        NSLog(@"队列状态变化 %@", transaction.description);
        // 如果小票状态是购买完成
        if (SKPaymentTransactionStatePurchased == transaction.transactionState) {
            NSLog(@"购买完成 %@", transaction.payment.productIdentifier);
            // 更新界面或者数据，把用户购买得商品交给用户
            // ...
            // 验证购买凭据
            [self verifyPruchase:transaction];
            // 将交易从交易队列中删除
            [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
        } else if (SKPaymentTransactionStateFailed == transaction.transactionState) {
            NSLog(@"购买失败 %@", transaction.payment.productIdentifier);
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            [loadingView closeView];
            [AppDelegate showHUDAndHide:transaction.error.localizedDescription view:[AppDelegate delegate].window];
        } else if (SKPaymentTransactionStateRestored == transaction.transactionState) {
            NSLog(@"恢复成功 %@", transaction.payment.productIdentifier);
            // 更新界面或者数据，把用户购买得商品交给用户
            // ...
            // 将交易从交易队列中删除
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            [loadingView closeView];
            [AppDelegate showHUDAndHide:@"恢复成功" view:[AppDelegate delegate].window];
        }
    }  
}
#pragma mark 验证购买凭据
- (void)verifyPruchase:(SKPaymentTransaction *)transaction
{
    // 验证凭据，获取到苹果返回的交易凭据
    // appStoreReceiptURL iOS7.0增加的，购买交易完成后，会将凭据存放在该地址
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    // 从沙盒中获取到购买凭据
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    // 在网络中传输数据，大多情况下是传输的字符串而不是二进制数据
    // 传输的是BASE64编码的字符串
     //BASE64 常用的编码方案，通常用于数据传输，以及加密算法的基础算法，传输过程中能够保证数据传输的稳定性
     //BASE64是可以编码和解码的
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    if (encodeStr.length<10) {
        [loadingView closeView];
        [AppDelegate showHUDAndHide:@"充值失败！" view:[AppDelegate delegate].window];
        return;
    }
    [MobClick event:@"2007"];
    RechargeRecord *recharge = [RechargeRecord new];
    recharge.uid = [UserAccount currentAccount].uid;
    recharge.rechargeRecordID = productId;
    NSDictionary *moneyDict = @{ReadPackage1:@"6",ReadPackage2:@"30",ReadPackage3:@"50",ReadPackage4:@"98",ReadPackage5:@"198",ReadPackage6:@"588"};
    recharge.money = moneyDict[buyingProduct];
    recharge.coin_num = coin_num;
    recharge.receiptBASE64 = encodeStr;
    recharge.time = [NSString stringWithFormat:@"%.f",[ZMYNetWorkAPI currentTime]];
    [[ZMYLKDB getLKDBHelper] updateRechargeRecord:recharge];
    //向服务器发生票据
    [[ZMYNetWorkAPI default]updateYuebi:recharge Response:^(NSDictionary *resultDic) {
        [loadingView closeView];
        [AppDelegate showHUDAndHide:@"恭喜您充值成功！" view:[AppDelegate delegate].window];
        [self closeView:nil];
    } error:^(NSString *errorStr) {
        [loadingView closeView];
        [AppDelegate showAlert:@"错误" message:@"服务器验证失败,请稍后在“我的”-“充值记录”里面选择账单进行恢复"];
    }];
    return;
    /*
    NSString *payload = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", encodeStr];
    NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];
    
    // 发送网络POST请求，对购买凭据进行验证
    NSURL *url = [NSURL URLWithString:@"https://sandbox.itunes.apple.com/verifyReceipt"];
    // 国内访问苹果服务器比较慢，timeoutInterval需要长一点
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    request.HTTPMethod = @"POST";
    request.HTTPBody = payloadData;
    
    // 提交验证请求，并获得官方的验证JSON结果
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    // 官方验证结果为空
    if (result == nil) {
        [loadingView closeView];
        [AppDelegate showHUDAndHide:@"验证失败" view:[AppDelegate delegate].window];
        return;
    }
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingAllowFragments error:nil];
    
    NSLog(@"%@", dict);
    
    if (dict != nil) {
        // 比对字典中以下信息基本上可以保证数据安全
        // bundle_id&application_version&product_id&transaction_id
        NSLog(@"验证成功");
    }
    
    return;
     */
}
-(void)showView{
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self];
    
//    NSBundle *bundle = [NSBundle mainBundle];
//    NSString *resPath = [bundle resourcePath];
//    NSString *filePath = [resPath stringByAppendingPathComponent:@"Home.html"];
//    [self.payWebView loadHTMLString:[NSString stringWithContentsOfFile:filePath]
//                    baseURL:nil];
    
    NSMutableURLRequest *reque = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]];
    reque.timeoutInterval = 10;
    [self.payWebView loadRequest:reque];
    [self.payWebView reload];
}
- (IBAction)closeView:(id)sender {
    if (self.delegate&&[self.delegate respondsToSelector:@selector(cancel)]) {
        [self.delegate cancel];
    }
    [[SKPaymentQueue defaultQueue]removeTransactionObserver:self];
    [self removeFromSuperview];
//    [self buyProduct:_productDict[ReadPackage1]];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

{
    NSString *urlString = [[request URL] absoluteString];
    urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if ([urlString rangeOfString:@"a=apple_order_web"].location!=NSNotFound) {
        [MobClick event:@"2005"];
    }
    NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
    if([urlComps count]==2 && [[urlComps objectAtIndex:0] isEqualToString:@"ios"])
    {
        NSArray *arrFucnameAndParameter = [(NSString*)[urlComps objectAtIndex:1] componentsSeparatedByString:@"/omituofo"];
        if (arrFucnameAndParameter.count==1) {
            if ([arrFucnameAndParameter[0] hasPrefix:@"ReadPackage"]) {
                arrFucnameAndParameter = [arrFucnameAndParameter[0] componentsSeparatedByString:@":"];
                NSString *funcStr = [arrFucnameAndParameter objectAtIndex:0];
                coin_num = [arrFucnameAndParameter objectAtIndex:1];
                [loadingView showView];
                [MobClick event:@"2006" attributes:@{@"ReadPackage" : @"funcStr"} counter:[coin_num intValue]];
                //向服务器请求订单号
                __weak typeof(self) weakSelf = self;
                [[ZMYNetWorkAPI default]getProductIdReadPackage:funcStr Response:^(NSDictionary *resultDic) {
                    buyingProduct = funcStr;
                    productId = [resultDic objectForKey:@"trade_no"];
                    [[SKPaymentQueue defaultQueue] addTransactionObserver:weakSelf];
                    [self requestProducts];
                } error:^(NSString *errorStr) {
                    [AppDelegate showHUDAndHide:errorStr view:[AppDelegate delegate].window];
                    [loadingView closeView];
                }];
                return NO;
            } else if ([arrFucnameAndParameter[0] isEqualToString:@"Lack_of_balance"]) {
                [self loadPayMoney];
                return NO;
            }else if ([arrFucnameAndParameter[0] isEqualToString:@"login"]){
                [AppDelegate showHUDAndHide:@"请登录后继续操作" view:[AppDelegate delegate].window];
                return NO;
            }else if ([arrFucnameAndParameter[0] isEqualToString:@"getnull"]){
                [AppDelegate showHUDAndHide:@"信息获取失败" view:[AppDelegate delegate].window];
                return NO;
            }else if ([arrFucnameAndParameter[0] isEqualToString:@"nopay"]){
                [AppDelegate showHUDAndHide:@"没有需要支付的信息 " view:[AppDelegate delegate].window];
                return NO;
            }
        }else if (arrFucnameAndParameter.count==2) {
            if([[arrFucnameAndParameter objectAtIndex:0] isEqualToString:@"PayChapters"]){
                NSURL *url = [NSURL URLWithString:[[NSString alloc]initWithData:[[NSData alloc]initWithBase64EncodedString:arrFucnameAndParameter[1] options:0] encoding:NSUTF8StringEncoding]];
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
                request.HTTPMethod = @"GET";
                // 章节支付URL
                NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
                
                // 官方验证结果为空
                if (result == nil) {
                    [AppDelegate showHUDAndHide:@"订阅章节失败，请重试" view:[AppDelegate delegate].window];
                    return NO;
                }
                
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingAllowFragments error:nil];
                if ([[dict objectForKey:@"ret"] isEqualToString:@"200"]||[[dict objectForKey:@"ret"] isEqualToString:@"202"]) {
                    [AppDelegate showHUDAndHide:@"订阅章节订阅成功，请继续下载" view:[AppDelegate delegate].window];
                    NSString *articleid = [[dict objectForKey:@"body"]objectForKey:@"articleid"];
                    NSArray *chapterIdArray = [[dict objectForKey:@"body"]objectForKey:@"chapterIds"];
                    if (articleid&&chapterIdArray.count>0) {
                        for (NSString *chapterId in chapterIdArray) {
                            BookReadPermissions *readPer = [BookReadPermissions new];
                            readPer.articleid = articleid;
                            readPer.chapterId = chapterId;
                            readPer.readPermissions = YES;
                            [readPer updateBookReadPermissions];
                        }
                    }
                    [self closeView:nil];
                    return NO;
                }else{
                    [AppDelegate showHUDAndHide:@"订阅章节订阅失败，请重试" view:[AppDelegate delegate].window];
                    [self closeView:nil];
                    return NO;
                }
                
            }else if([[arrFucnameAndParameter objectAtIndex:0] isEqualToString:@"sub_list_texts"]){
                [self closeView:nil];
                NSArray *chapter = [arrFucnameAndParameter[1] componentsSeparatedByString:@"/mamimamihong"];
                if ([self.delegate respondsToSelector:@selector(chargeForChaptersNetwork:)]) {
                    [self.delegate chargeForChaptersNetwork:chapter];
                }
                return NO;
            }
        }
        [AppDelegate showHUDAndHide:@"网络错误，请稍后再试" view:[AppDelegate delegate].window];
        return NO;
    }
    if ([urlComps count]==2) {
        if ([[urlComps objectAtIndex:0] isEqualToString:@"http"]) {
            [loadingView showView];
            return YES;
        }
        
    }
    return YES;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if (title.length>1) {
        self.titleNameLabel.text = title;
    }
    [loadingView closeView];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [loadingView closeView];
    self.payWebView.hidden = YES;
}
- (void)reloadWebAgain:(id)sender {
    self.payWebView.hidden = NO;
    NSMutableURLRequest *reque = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]];
    reque.timeoutInterval = 10;
    [self.payWebView loadRequest:reque];
}
#pragma mark 加载充值页面
-(void)loadPayMoney{
    UserAccount *user = [UserAccount currentAccount];
    if (!user) {
        [AppDelegate showHUDAndHide:@"请登录后继续操作" view:[AppDelegate delegate].window];
        [self closeView:nil];
        return;
    }
    self.webUrl = [NSString stringWithFormat:@"http://%@/web/qy_apple.php?a=apple_order_web&uid=%@&token=%@&srcid=iOS&ct=iOS&pay_way=iOS",SERVER,user.uid,user.token];
    NSURLRequest *reque = [NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]];
    [self.payWebView loadRequest:reque];
}
@end
